package no.ntnu.fp.connection;

import java.util.HashMap;
import java.util.Map;

import no.ntnu.fp.exceptions.UnsupportedMessageException;
import no.ntnu.fp.messages.Message;
import no.ntnu.fp.messages.MessageCode;

/**
 * A class used to translate messages. Designed as a singleton to
 * ease sharing between different {@link MessageHandler}s.
 * @author benjamin
 *
 */
final public class MessageTranslator {
	
	private final Map<MessageCode, Message> messages = new HashMap<MessageCode, Message>();
	
	public Message translateMessage(String message) {
		String[] returnedValues = extractMessageCode(message);
		MessageCode messageCode = MessageCode.valueOf(returnedValues[0]);
		String restOfXml = returnedValues[1];
		Message appropriateMessage = messages.get(messageCode);
		if (appropriateMessage == null) {
			throw new UnsupportedMessageException(
					"No Message registered for message code in translator", messageCode);
		}
		return appropriateMessage.fromXmlString(restOfXml);
	}
	
	/**
	 * This method extracts the {@link MessageCode} contained in the 
	 * xml of the message received, and returns an array containing
	 * as its first object the {@code MessageCode} parsed, and the
	 * rest of the xml to be parsed as its second value.
	 * @param message The message from which a {@code MessageCode} should be parsed
	 * @return An array of structure {@code [parsedCode:MessageCode, restOfXml:String] } 
	 */
	private String[] extractMessageCode(String message) {
		int firstBracketIndex = message.indexOf("<");
		return new String[]{message.substring(0, firstBracketIndex), message.substring(firstBracketIndex)};
	}
	
	private static MessageTranslator instance;
	
	public static synchronized MessageTranslator createInstance(Map<MessageCode, Message> messages) {
		if (instance == null) {
			instance = new MessageTranslator();
			instance.messages.putAll(messages);
			return instance;
		} else {
			throw new IllegalStateException("MessageTranslator is already initialized");
		}
	}
	
	public static synchronized MessageTranslator getInstance() {
		if (instance == null) {
			throw new IllegalStateException("MessageTranslator is not initialized");
		} else {
			return instance;
		}
	}
	
	private MessageTranslator() { }
}
